<?php

namespace App\Utils;

use App\Exceptions\LogicException;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\Log;

/**
 * dec
 *
 * Class MiniprogramUtil 小程序工具类，需要安装 "overtrue/wechat": "~4.0",
 *
 * @package App\Utils
 * @author WANGWEI 2025-06-22
 */
class MiniprogramUtil
{
    /**
     * @var MiniprogramUtil
     */
    private static $instance = null;

    /**
     * @var array
     */
    private $config;

    /**
     * @var \EasyWeChat\MiniProgram\Application
     */
    private $app;

    /**
     * MiniprogramUtil constructor.
     */
    private function __construct()
    {
        $this->config = config('wechat.mini_program.default');
        $this->app = Factory::miniProgram($this->config);
    }

    /**
     * 获取实例
     * @return MiniprogramUtil
     */
    public static function getInstance(): MiniprogramUtil
    {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 获取小程序session信息
     * @param string $code 登录code
     * @return array
     * @throws LogicException
     */
    public function getSession(string $code): array
    {
        if (empty($code)) {
            throw new LogicException('登录凭证不能为空');
        }

        try {
            $result = $this->app->auth->session($code);

            if (isset($result['errcode']) && $result['errcode'] != 0) {
                Log::error('小程序登录失败', ['code' => $code, 'result' => $result]);
                throw new LogicException('登录失败：' . ($result['errmsg'] ?? '未知错误'));
            }

            return $result;
        } catch (\Exception $e) {
            Log::error('小程序登录异常', ['code' => $code, 'error' => $e->getMessage()]);
            return [];
        }
    }

    /**
     * 防止克隆实例
     */
    private function __clone()
    {
    }
}